package com.tegtech.module.captcha.service;

import org.springframework.beans.factory.annotation.Autowired;

import com.tegtech.common.exception.BusinessExceptionUtil;
import com.tegtech.module.captcha.cache.CaptchaCache;
import com.tegtech.module.captcha.constant.CaptchaKey;
import com.tegtech.module.captcha.domain.CaptchaRule;
import com.tegtech.module.captcha.enums.CaptchaHttpStatus;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class AbstractCaptchaMessageService implements ICaptchaMessageService {
	
	@Autowired
	protected CaptchaCache captchaCache;
	
	@Override
	public void sendCaptchaMesage(String account, CaptchaRule captchaRule) {
		String captchaType = captchaRule.getKey();
		// 检验发送次数是否已达上限
		if(captchaRule.getMaxNum() != -1 && captchaCache.getTodayMessageNum(account, captchaType) >= captchaRule.getMaxNum()) {
			BusinessExceptionUtil.i18nEx(CaptchaHttpStatus.SEND_NUM_LIMIT);
		}
		// 校验发送时间间隔
		Long lastTime = MapUtil.getLong(captchaCache.getCodeMap(account, captchaType), CaptchaKey.CAPTCHA_TIME);
		if(lastTime != null && System.currentTimeMillis() - lastTime < captchaRule.getIntervalTime() * 1000) {
			BusinessExceptionUtil.i18nEx(CaptchaHttpStatus.SEND_INTERVAL_LIMIT, captchaRule.getIntervalTime());
		}
		// 发送短信验证码
		String code = RandomUtil.randomNumbers(captchaRule.getCodeLength());
		this.sendCaptchaMessage(account, code, captchaRule);
		// 缓存验证码
		captchaCache.cacheCode(account, code, captchaType);
		// 更新短信发送次数
		captchaCache.incrMessageNum(account, captchaType);
		log.info("验证码发送成功，账号：【{}】，验证码：【{}】", account, code);
	}

	/**
	 * 发送验证码，由子类实现
	 * @param account
	 * @param code
	 * @param captchaRule
	 */
	protected abstract void sendCaptchaMessage(String account, String code, CaptchaRule captchaRule);
	
}
